using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace MTRC.ODMS.Web.SOM.Popup
{
    /// <summary>
    /// Author:SQB
    /// </summary>
    public partial class SetRegEventTime : BasePage_SOM 
    {
        #region Web

        override protected void OnInit(EventArgs e)
        {

            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>

        /// </summary>
        private void InitializeComponent()
        {
            this.ChangeLanguage += new MTRC.ODMS.Web.BasePage.ChangeLanguageEventHandler(this.SetLanguage_Click);
        }

        #endregion


        protected int DetailLength
        {
            get 
            {
                if (ViewState["DetailLength"] != null)
                {
                    return int.Parse(ViewState["DetailLength"].ToString());
                }
                else
                {
                    return 20;
                }
            }
            set{ViewState["DetailLength"]=value;}
    
        }

        /// <summary>
        /// StationEventID  ISU45
        /// add by gordon 20160205
        /// </summary>
        protected int StationEventID
        {
            get
            {
                //update by gordon 20160218 ISU45
                //if (ViewState[MTRC.ODMS.BLL.COM.Session.SOM_StationEventID] == null)
                //{
                //    return -1;
                //}
                //else
                //{
                //    return int.Parse(ViewState[MTRC.ODMS.BLL.COM.Session.SOM_StationEventID].ToString());
                //}
                int stationEventID = -1;
                int.TryParse(Request.QueryString["StationEventID"], out stationEventID);
                return stationEventID > 0 ? stationEventID : -1;
                //update end by gordon 20160218 ISU45
            }
            //Comment by gordon 20160218 ISU45
            //set
            //{
            //    ViewState[MTRC.ODMS.BLL.COM.Session.SOM_StationEventID] = value;
            //}
        }

        /// <summary>
        /// EventStatusID
        /// add by gordon 20160226 - GE Allow user to amend the description even if the event has been compelted
        /// </summary>
        protected string EventStatusID
        {
            get {
                return string.IsNullOrEmpty(Request.QueryString["EventStatusID"]) ? "-1" : Request.QueryString["EventStatusID"];
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            SetPageLoad();
            if(!IsPostBack)
            {
                //comment by gordon 20160218 ISU45
                ////add by gordon 20160205 ISU45
                //if (!string.IsNullOrEmpty(Request.QueryString["StationEventID"]))
                //{
                //    StationEventID = int.Parse(Request.QueryString["StationEventID"]);
                //}
                ////add end by gordon 20160205
                //comment end by gordon 20160218

                // add by dylan 20151030 for u275.1 
                this.grdAmendReason.PageSize = this.GridViewPageDefaultSize();
                SetLanguage();

                //add by gordon 20160226 - GE Allow user to amend the description even if the event has been compelted
                if (IsMatch())
                {
                    //add by tim 20150513 for show confirm button
                    //this.btnSaveAndConfirmReturn.Visible = true;
                    //this.btnSaveReturn.Visible = false;
                    this.btnSaveReturn.Text = this.GetLabel("COM_SaveAndReturn");
                    //end add
                    grdAmendReason.Columns[1].Visible = true;
                }
            }
            
        }

        private void SetPageLoad()
        {
            DetailLength = int.Parse(MTRC.ODMS.DAL.CommonData.GetNumVal("SOM_DetailLength").ToString());
            //if (this.Request["StationEventID"] != null)
            //{
            //    this.btnSaveReturn.Enabled = false;
            //}
            this.btnCancel.Attributes.Add("onclick", "javascript:window.close(); return false;");
            this.btnSaveReturn.Attributes.Add("onclick", "javascript:return SaveCheck('" + this.GetMessage("COM_EntryAllFields") + "', '" + this.GetMessage("SOM_AmendTimesReachMaximumTimes") + "');");
        }

        private void BindData()
        {
            DataTable dt= new DataTable();            
            if (this.Request["StationEventID"] != null || this.StationEventID !=-1)
            {
                int stationEventID;
                if (this.Request["StationEventID"] != null)
                {
                    stationEventID = int.Parse(this.Request["StationEventID"].ToString().Trim());

                }
                else
                {
                    stationEventID = this.StationEventID;
                }
                int timeType;
                if (this.Request["TimeType"] != null)
                {
                    timeType = int.Parse(this.Request["TimeType"].ToString().Trim());
                }
                else
                {
                    timeType =1;
                }
                dt = MTRC.ODMS.DAL.SOM.Event.StationEventAmendTimeDa.GetAllStaEventAmdTimeByStaEventID(this.LangCode, timeType,  stationEventID); //this.Request["StationEventID"].ToString().Trim());
                this.grdAmendReason.DataSource = dt.DefaultView;
                this.grdAmendReason.GetLabelFunction = new APJ.Web.UI.WebControls.GetLabel(this.GetLabel);
                this.grdAmendReason.DataBind();
                
                //hdnIsReachMaxAmendTimes
                //huangyao 20081025 --add function to control maximum amend times
                string maximumTimesParaName = "";
                string pageID = string.Concat(Request.QueryString["pageID"].Trim());
                if (pageID.ToUpper() == "AREntryArrival".ToUpper())
                { 
                    maximumTimesParaName = "SOM_AR_AmendArrivalTime_Times";
                }
                else if (pageID.ToUpper() == "FireProtectionEntry".ToUpper())
                {
                    maximumTimesParaName = "SOM_FireLink_AmendEventTime_Times";
                }
                else if (pageID.ToUpper() == "AL".ToUpper())
                {
                    maximumTimesParaName = "SOM_AssetLoan_AmendEventTime_Times";
                }
                else if (pageID.ToUpper() == "GeneralEventEntry".ToUpper())
                {
                    maximumTimesParaName = "SOM_GeneralEvent_AmendEventTime_Times";
                }
                else if (pageID.ToUpper() == "DutySCEntry".ToUpper())
                {
                    maximumTimesParaName = "SOM_DutySC_AmendEventTime_Times";
                }

                if(this.grdAmendReason.Rows.Count - 1 >= MTRC.ODMS.DAL.COM.Util.Int32FromDB(MTRC.ODMS.DAL.CommonData.GetNumVal(maximumTimesParaName)) )
                {
                    this.hdnIsReachMaxAmendTimes.Value = "Y";
                }
                //-------end----------------------------------------------------
            }
            else
            {
                this.grdAmendReason.Visible = false;
            }
        }
        private void SetLanguage()
        {
            //huangyao modified 20081124 fixed issue 0696
            //if (int.Parse(Request.QueryString["timeType"].ToString()) == 2)
            //{
            //    this.lblArrivalStationTime.Text = this.GetLabel("SOM_StationDepartureTime", true);
            //}
            //else
            //{
            //    this.lblArrivalStationTime.Text = this.GetLabel("SOM_ArrivalTime", true);
            //}
            //update by gordon 20160226 - GE Allow user to amend the description even if the event has been compelted
            //this.lblArrivalStationTime.Text = this.GetLabel("SOM_OriginalEventTime", true);
            this.lblArrivalStationTime.Text = this.GetLabel("SOM_Amend_EventTime",true);
            //---------------
            this.lblAmendReason.Text = this.GetLabel("SOM_AmendReason",true);
            //add by tim 20150513 for show confirm button
            //this.btnSaveReturn.Text = this.GetLabel("COM_SaveAndReturn");
            this.btnSaveReturn.Text = this.GetLabel("COM_RM_Confirm");
            this.btnCancel.Text = this.GetLabel("COM_Cancel");
            this.lblHistory.Text = this.GetLabel("SOM_HistoryAmendment");
            BindData();
        }

        protected void grdAmendReason_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if(e.Row.RowType== DataControlRowType.DataRow)
            {
                //update by gordon 20160225 - GE Allow user to amend the description even if the event has been compelted
                //((Button)(e.Row.Cells[2].FindControl("btnShowDetails"))).Attributes.Add("onclick", "javascript:ShowDetails(" + ((TextBox)(e.Row.Cells[1].FindControl("txtReasonValue"))).ClientID.ToString() + "); return false;");
                //if (((TextBox)(e.Row.Cells[1].FindControl("txtReasonValue"))).Text.Trim().Length >= DetailLength)
                //{
                //    ((Label)(e.Row.Cells[1].FindControl("lblReasonShowShort"))).Text = ((TextBox)(e.Row.Cells[1].FindControl("txtReasonValue"))).Text.Substring(0, DetailLength) + "...";
                //}
                ((ImageButton)(e.Row.Cells[4].FindControl("btnShowDetails"))).Attributes.Add("onclick", "javascript:ShowDetails(" + ((TextBox)(e.Row.Cells[3].FindControl("txtReasonValue"))).ClientID.ToString() + "); return false;");
                //add by tim 20160503 pop description
                ((ImageButton)(e.Row.Cells[2].FindControl("btnShowDescription"))).Attributes.Add("onclick", "javascript:ShowDetails(" + ((TextBox)(e.Row.Cells[2].FindControl("txtDescriptionValue"))).ClientID.ToString() + "); return false;");
                if (((TextBox)(e.Row.Cells[3].FindControl("txtReasonValue"))).Text.Trim().Length >= DetailLength)
                {
                    ((Label)(e.Row.Cells[3].FindControl("lblReasonShowShort"))).Text = ((TextBox)(e.Row.Cells[3].FindControl("txtReasonValue"))).Text.Substring(0, DetailLength) + "...";
                }
                //update by gordon 20160225 - GE Allow user to amend the description even if the event has been compelted

                //add by gordon 20160225 - GE Allow user to amend the description even if the event has been compelted

                if (IsMatch())
                {
                    TableCell tdDesc = e.Row.Cells[1];
                    TableCell tdAmendTime = e.Row.Cells[2];
                    Label lblDescription = tdDesc.FindControl("lblDescription") as Label;
                    if (lblDescription.Text.Trim().Length >= DetailLength)
                    {
                        lblDescription.Text = lblDescription.Text.Substring(0, DetailLength) + "...";
                    }
                }

                //add end by gordon 20160225 - GE Allow user to amend the description even if the event has been compelted

                //e.Row.Cells[0].Text = this.FormatDateTime(e.Row.Cells[0].Text,true);
            }
        }

        protected void grdAmendReason_NeedDataBind()
        {
            BindData();
        }
         
        private void SetLanguage_Click(object sender, System.EventArgs e)
        {
            SetLanguage();
        }

        //------------------ Add by zengshunbo 2008-12-23 -----------------------

        protected void btnSaveReturn_Click(object sender, EventArgs e)
        {
            MTRC.ODMS.Model.SOM.Event.StationEventAmendTimeInfo eventAmendTimeInfo = new MTRC.ODMS.Model.SOM.Event.StationEventAmendTimeInfo();

            if (chkEventTime.Checked ||(!IsMatch()))//add by gordon 20160225 - GE Allow user to amend the description even if the event has been compelted
            {
                int amendEventTimeRangeParameter = Convert.ToInt32(ODMS.DAL.CommonData.GetNumVal("SOM_AmendEventTime_Range"));

                DateTime nowDateTime = ClearSecond(ODMS.DAL.COM.Util.GetCurrentSystemTime());
                DateTime inputDateTime = ClearSecond(this.dtbArrivalStationTime.GetDateTime());

                //add by gordon 20160218 ISU28
                int _yearMin = 0;
                int.TryParse(APJ.Util.Utility.GetAppSetting("SOM_DBMinDate_Year"), out _yearMin);
                _yearMin = _yearMin > 0 ? _yearMin : 1753;

                int _yearMax = 0;
                int.TryParse(APJ.Util.Utility.GetAppSetting("SOM_DBMaxDate_Year"), out _yearMax);
                _yearMax = _yearMax > 0 ? _yearMax : 9999;

                if (inputDateTime.Year < _yearMin || inputDateTime.Year > _yearMax)
                {
                    Alert(this.GetMessage("SOM_AmendTime_Invalid"));
                    return;
                }
                //add end by gordon 20160218 ISU28

                if (amendEventTimeRangeParameter >= 0)
                {
                    if (inputDateTime >= nowDateTime && inputDateTime <= nowDateTime.AddMinutes(amendEventTimeRangeParameter))
                    {
                        this.ClientScript.RegisterStartupScript(typeof(BasePage), "btnSaveReturnClick", "<script language='javascript'>btnSaveReturnClick();</script>");
                        //string writeScript = "<script>btnSaveReturnClick();</script>";
                        //Response.Write(writeScript);
                    }
                    else
                    {
                        Alert(this.GetMessage("SOM_AmendEventTime_Range", this.LangCode));
                    }
                }
                else if (amendEventTimeRangeParameter < 0)
                {
                    //string writeScript = "<script>btnSaveReturnClick();</script>";
                    //Response.Write(writeScript);
                    this.ClientScript.RegisterStartupScript(typeof(BasePage), "btnSaveReturnClick", "<script language='javascript'>btnSaveReturnClick();</script>");
                }

                //add by gordon 20150814 U138
                if (!string.IsNullOrEmpty(hdnGenH.Value))
                {
                    hdnGenD.Value = this.FormatDateTime(inputDateTime.AddMinutes(Convert.ToDouble(hdnGenH.Value) * 60), true, false);
                }

            }

            else//add by gordon 20160225 - GE Allow user to amend the description even if the event has been compelted
            {
                eventAmendTimeInfo.OriginalDescription = HttpUtility.HtmlEncode(this.txtAmendDescription.Text.Trim());
                this.ClientScript.RegisterStartupScript(typeof(BasePage), "btnSaveReturnClick", "<script language='javascript'>btnSaveReturnClick();</script>");
            }


            //add by tim 20160516 for SIT20
            String btnText = this.GetLabel("COM_SaveAndReturn");
            if (this.btnSaveReturn.Text == btnText)
            {

                DateTime eventTime = new DateTime();

                eventTime = this.ConvertToDateTime(this.dtbArrivalStationTime._dateText.Text + " " + this.dtbArrivalStationTime._dateTimeText.Text + ":00");
                
                DateTime initialEventTime = MTRC.ODMS.DAL.COM.Util.GetCurrentSystemTime();

                eventAmendTimeInfo.TimeType = 1; //hard code

                eventAmendTimeInfo.Reason = this.txtAmendReason.Text.Trim();
                eventAmendTimeInfo.AmendUser = this.ODMUser.ID;
                eventAmendTimeInfo.LastUpdTime = DateTime.Now;

                if (this.chkDescription.Checked == true)
                {

                    eventAmendTimeInfo.OriginalDescription = HttpUtility.HtmlEncode(this.txtAmendDescription.Text.Trim()) ;
                    //eventAmendTimeInfo.OriginalDescription = txtDescriptionBefore.Value;
                    //stationEventModel.Description = HttpUtility.HtmlEncode(hdnAmendDescription.Value);
                }

                if (this.chkEventTime.Checked == true)
                {
                    eventAmendTimeInfo.OriginalEventTime = eventTime;
                    if (initialEventTime != eventTime)
                    {
                        eventAmendTimeInfo.InitialEventTime = initialEventTime;
                    }
                }


                string strXMLAmendTime = string.Empty;
                if (!string.IsNullOrEmpty(eventAmendTimeInfo.Reason))
                {
                    strXMLAmendTime = eventAmendTimeInfo.ToDBXML();
                }

                if (this.chkDescription.Checked == true && this.chkEventTime.Checked == false)
                {
                    DAL.SOM.Event.StationEventGeneralEventDa.Submit(this.StationEventID, strXMLAmendTime,"DescriptionOnly");
                }
                else if (this.chkDescription.Checked == false && this.chkEventTime.Checked == true)
                {
                    DAL.SOM.Event.StationEventGeneralEventDa.Submit(this.StationEventID, strXMLAmendTime, "EventTimeOnly");
                }
                else
                {
                    DAL.SOM.Event.StationEventGeneralEventDa.Submit(this.StationEventID, strXMLAmendTime);
                }
                // end add
            };







        }

        private DateTime ClearSecond(DateTime dt)
        {
            DateTime tmpTime = new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, 0);

            return tmpTime;
        }

        //------------------ End add by zengshunbo 2008-12-23 -----------------------

        //add by gordon 20160225 - GE Allow user to amend the description even if the event has been compelted
        private bool IsMatch()
        {
            return Request.QueryString["ReadOnly"].ToUpper() == "TRUE" && Request.QueryString["PageID"].ToUpper() == "GeneralEventEntry".ToUpper() && EventStatusID == "2";
        }

   
        //add end by gordon 20160225 - GE Allow user to amend the description even if the event has been compelted
    }
}
